package com.sitech.ibnms.util.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
import java.util.Vector;

import org.apache.log4j.Logger;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.ChannelSftp.LsEntry;

/**
 * SFTP工具类
 *
 * @author   LINXC
 */
public class SFTPClient implements FTPIF{
	private Logger logger = Logger.getLogger(SFTPClient.class);

	private ChannelSftp sftp = null;
	private Session sshSession = null;
	
	public void login(String host, String username, String password)
			throws Exception {
		this.connect(host, 22, username, password);
	}

	public boolean store(String uploadFile, String toRfileName)
			throws Exception {
		String directory = toRfileName.substring(0, toRfileName
				.lastIndexOf("/"));
		return upload(directory, uploadFile);
	}
	@Override
	public boolean get(String downloadFile, String toLFileName)
			throws Exception {
		// TODO Auto-generated method stub
		String directory = downloadFile.substring(0, downloadFile
				.lastIndexOf("/"));
		return this.download(directory, downloadFile, toLFileName, sftp);
	}
	/***************************************************************************
	 * 连接SFTP服务器
	 * 
	 * @param host
	 *            主机
	 * @param port
	 *            端口
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return
	 **************************************************************************/
	public boolean connect(String host, int port, String username,
			String password) {
		try {
			JSch jsch = new JSch();
			jsch.getSession(username, host, port);
			sshSession = jsch.getSession(username, host, port);
			sshSession.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no"); 
			sshSession.setConfig(sshConfig);
			sshSession.connect();
			Channel channel = sshSession.openChannel("sftp");
			channel.connect();
			sftp = (ChannelSftp) channel;
			logger.info("Create sftp connection successful. ");
			return true;
		} catch (Exception e) {			
			logger.error("Create sftp connection failed. ", e);
			return false;
		}
	}

	/***************************************************************************
	 * 上传文件
	 * 
	 * @param directory
	 *            上传的目录
	 * @param uploadFile
	 *            要上传的文件
	 * @param sftp
	 **************************************************************************/
	public boolean upload(String directory, String uploadFile) {
		try {
			sftp.cd(directory);
			File file = new File(uploadFile);
			sftp.put(new FileInputStream(file), file.getName());

			logger.info("Upload file[" + uploadFile + "] successful. ");
			return true;
		} catch (Exception e) {
			logger.error("Upload file[" + uploadFile + "] failed. ", e);
			return false;
		}
	}

	/***************************************************************************
	 * 下载文件
	 * 
	 * @param directory
	 *            下载目录
	 * @param downloadFile
	 *            下载的文件
	 * @param saveFile
	 *            存在本地的路径
	 * @param sftp
	 **************************************************************************/
	public boolean download(String directory, String downloadFile,
			String saveFile, ChannelSftp sftp) {
		try {
			sftp.cd(directory);
			File file = new File(saveFile);
			sftp.get(downloadFile, new FileOutputStream(file));
			
			logger.info("Download file[" + downloadFile + "] successful. ");
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("Download file[" + downloadFile + "] failed. ");
			return false;
		}
	}

	/***************************************************************************
	 * 删除文件
	 * 
	 * @param directory
	 *            要删除文件所在目录
	 * @param deleteFile
	 *            要删除的文件
	 * @param sftp
	 **************************************************************************/
	public void delete(String directory, String deleteFile) {
		try {
			sftp.cd(directory);
			sftp.rm(deleteFile);
			logger.info("Delete file[" + deleteFile + "] successful. ");
		} catch (Exception e) {
			logger.info("Delete file[" + deleteFile + "] failed. ");
		}
	}

	/***************************************************************************
	 * 列出目录下的文件
	 * 
	 * @param directory
	 *            要列出的目录
	 * @param sftp
	 * @return
	 * @throws SftpException
	 **************************************************************************/
	@SuppressWarnings("unchecked")
	public Vector<LsEntry> listFiles(String directory)
			throws SftpException {
		return sftp.ls(directory);
	}
	
	public static void main(String[] args) throws Exception {
		SFTPClient client = new SFTPClient();
		
		if(client.connect("172.21.0.69", 22, "yfbnms", "yfbnms")){
			Vector<LsEntry> list = client.listFiles("/yfbnms");
			for(LsEntry entry: list){
				System.out.println(entry);
			}
		}
		client.logout();
	}


	public void logout() throws Exception {
		if(sftp != null){
			sftp.disconnect();
		}
		
		if(sshSession != null){
			sshSession.disconnect();
		}
		
	}

	
}
